<?php

namespace Module\Cms;

use Manager\Comment as Manager;
use Base\Contents;
use W3\Router;
use W3\Exception;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 反馈提交组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Feedback extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'feedback',	
			
		], true);
	}

    public function action()
    {
        if (!$this->auth->hasLogin()) {
			throw new Exception(__('请登录.'), 403);
        }

		/** 内容对象 */ 
        $contents = Router::resource($this->request->permalink, $this->request->method());

        /** 判断内容是否存在 */
        if (false !== $contents && $contents instanceof Contents && $contents->have() && $contents->is('single')) {
			
            /** 评论关闭 */
            if (!$contents->allow('comment')) {
				throw new Exception(__('对不起,此内容的反馈被禁止.'), 403);
            }
			
            /** 检查来源 */
            if ($this->config->commentsCheckReferer) {
                $referer = $this->request->referer();
                if (empty($referer)) {
					throw new Exception(__('对不起,评论来源页错误.'), 403);
                }
                $refererPart = parse_url($referer);
                $currentPart = parse_url($contents->permalink);

                if ($refererPart['host'] != $currentPart['host'] || 0 !== strpos($refererPart['path'], $currentPart['path'])) {
					
                        //自定义首页支持
                        if ($contents->cid == $this->config->frontPage) {
                            $currentPart = parse_url(rtrim($this->config->siteUrl, '/') . '/');

                            if (
                                $refererPart['host'] != $currentPart['host'] ||
                                0 !== strpos($refererPart['path'], $currentPart['path'])
                            ) {
                                throw new Exception(__('评论来源页错误.'), 403);
                            }
                        } else {
                            throw new Exception(__('评论来源页错误.'), 403);
                        }

                }
            }
			
            /** 检查uid评论间隔 */
            if (!$this->auth->pass('editor', true) && $contents->uid != $this->auth->uid && $this->config->commentsPostIntervalEnable) {
				
                $latestComment = $this->db->select('created')
				    ->from('table.comments')
					->where('uid = ?', $this->auth->uid)
					->order('created', 'DESC')
					->limit(1)
					->fetch();
					
                if ($latestComment && ($this->config->time - $latestComment['created'] > 0 && $this->config->time - $latestComment['created'] < $this->config->commentsPostInterval)) {
					throw new Exception(__('对不起, 您的发言过于频繁, 请稍侯再次发布.'), 403);
                }
            }

			$comment = array(
				'cid' => $contents->cid, 
				'created' => $this->config->time, 
				'ip' => $this->request->ip(true), 
				'uid' => $this->auth->uid, 
				'text' => $this->request->text, 
				'ownerId' => $contents->uid,
                'type' => 'comment',
                'status' => !$contents->allow('edit')
                    && $this->config->commentsRequireModeration ? 'waiting' : 'approved'
			);
			
            /** 判断父节点 */
            if ($parentId = $this->request->filter('int')->get('parent')) {
                if ($this->config->commentsThreaded && ($parent = $this->db->select('coid', 'cid')->from('table.comments')->where('coid = ?', $parentId)->fetch()) && $contents->cid == $parent['cid']) {
                    $comment['parent'] = $parentId;
                } else {
					throw new Exception(__('父级评论不存在.'), 403);
                }
            }
            if (empty($comment['text'])) {
				throw new Exception(__('必须填写评论内容.'), 403);
            }

            /** 评论者之前须有评论通过了审核 */
            if (!$this->config->commentsRequireModeration && $this->config->commentsWhitelist) {
                if (
                    $this->db->select()->from('table.comments')->where(
                        'uid = ? AND status = ?',
                        $this->auth->uid,
                        'approved'
                    )->count()
                ) {
                    $comment['status'] = 'approved';
                } else {
                    $comment['status'] = 'waiting';
                }
            }

            /** 评论接口 */
			$comment = do_action('comment', $this, false, $comment, $contents);
			
			$commentId = $this->addComment($comment);
            $this->db->select()
			    ->from('table.comments')
			    ->where('coid = ?', $commentId)
                ->limit(1)
				->fetch([$this, 'push']);

            /** 评论完成接口 */
			do_action('comment_finish', $this);
			
			$this->goBack('#' . $this->theId);
			
        } else {
			throw new Exception(__('请求的资源不存在'), 404);
        }
    }
}

